using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.ErrorCode;
using RBAC.Interstructrue;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement.Billing;
using System.Linq;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement.Billing
{
    /// <summary>
    /// 获取开票通知单详情处理器
    /// </summary>
    public class GetBillingNoticeDetailHandler : IRequestHandler<GetBillingNoticeDetailCommand, APIResult<BillingNoticeDetailDto>>
    {
        private readonly RBACDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public GetBillingNoticeDetailHandler(RBACDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 处理获取开票通知单详情请求
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>开票通知单详情</returns>
        public async Task<APIResult<BillingNoticeDetailDto>> Handle(GetBillingNoticeDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询开票通知单及关联的物料明细
                var billingNotice = await _context.BillingAccountings
                    .Include(b => b.BillingMaterials)
                    .Where(b => b.BillNumber == request.BillNumber && !b.IsDeleted)
                    .FirstOrDefaultAsync(cancellationToken);

                if (billingNotice == null)
                {
                    return new APIResult<BillingNoticeDetailDto>
                    {
                        Code = APIEnums.Fail,
                        Msg = "未找到指定的开票通知单"
                    };
                }

                // 构建返回数据 - 使用中文状态名
                var result = new BillingNoticeDetailDto
                {
                    Id = billingNotice.Id,
                    BillNumber = billingNotice.BillNumber,
                    BusinessType = billingNotice.BusinessType,
                    CustomerName = billingNotice.CustomerName,
                    BankName = billingNotice.BankName,
                    AccountNumber = billingNotice.ProductCode,
                    TaxNumber = billingNotice.TaxId,
                    AddressPhone = billingNotice.AddressPhone,
                    DeliveryEmail = billingNotice.DeliveryEmail,
                    BillDate = billingNotice.BillDate,
                    Operator = billingNotice.Operator,
                    InvoiceType = billingNotice.InvoiceType,
                    RedReason = billingNotice.RedReason,
                    Remarks = billingNotice.Remarks,
                    Status = billingNotice.Status,
                    BusinessStatus = billingNotice.BusinessStatus,
                    // 添加中文状态名字段
                    BillStatus = billingNotice.BillStatus,
                    Items = billingNotice.BillingMaterials
                        .Where(m => !m.IsDeleted)
                        .Select(m => new BillingMaterialDetailDto
                        {
                            Id = m.Id,
                            OrderNumber = m.OrderNumber,
                            MaterialCode = m.MaterialCode,
                            MaterialName = m.MaterialName,
                            Unit = m.Unit,
                            Quantity = m.Quantity,
                            UnitPrice = m.UnitPrice,
                            Amount = m.Amount,
                            InvoiceName = m.InvoiceName,
                            Remarks = m.Remarks
                        })
                        .ToList()
                };

                return new APIResult<BillingNoticeDetailDto>
                {
                    Code = APIEnums.Success,
                    Msg = "获取开票通知单详情成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                return new APIResult<BillingNoticeDetailDto>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取开票通知单详情失败：" + ex.Message
                };
            }
        }
    }
}